#!/usr/bin/env python3
# Author:liang futing
# @Time :2020/4/29 15:37
import os
import threading
import json
from django.contrib.auth import get_user_model
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse, HttpResponse
from django.shortcuts import render, redirect, reverse
from django.views.decorators.clickjacking import xframe_options_deny, xframe_options_exempt, xframe_options_sameorigin
from oldblog import settings

from bs4 import BeautifulSoup
from blog.models import Article

User = get_user_model()


@login_required
def cn_backend(request):
    article_list = Article.objects.filter(user=request.user)
    return render(request, 'backend/backend.html', locals())


@login_required

def add_article(request):
    if request.method == "POST":
        title = request.POST.get("title")
        content = request.POST.get("content")

        soup = BeautifulSoup(content, "html.parser")
        # 防御XSS攻击
        for tag in soup.find_all():
            print(tag.name)
            if tag.name == "script":
                tag.decompose()

        # 如何文章摘要保存 ，通过Beautifulsoup模块来截取文本的中的有效字符串
        desc = soup.text[0:150] + '...'

        Article.objects.create(title=title, content=str(soup), user=request.user, desc=desc)
        return redirect(reverse("cn_backend"))
    return render(request, 'backend/add_article.html')


@login_required
@xframe_options_exempt
def upload(request):
    # print(request.FILES)
    if request.method == "POST":
        # print(request, request.FILES)
        img = request.FILES.get("upload_img")

        path = os.path.join(settings.MEDIA_ROOT, 'add_article_img', img.name)
        with open(path, 'wb') as f:
            for line in img:
                f.write(line)

        response = {
            'error': 0,
            'url': "/media/add_article_img/%s" % img.name,
            "message": 'ok'
        }
        # print(JsonResponse(response))

        # ret = json.dumps(response)
        # return HttpResponse(ret)
        return JsonResponse(response)
